package com.chen.reggie.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.reggie.common.BaseContext;
import com.chen.reggie.common.CustomException;
import com.chen.reggie.mapper.OrderMapper;
import com.chen.reggie.pojo.*;
import com.chen.reggie.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;


    /**
     * @date 2022/9/7
     * @param [orders]
     * @return void
     * 用户下单
     **/
    @Transactional
    public void submit(@RequestBody Orders orders) {
        //1.获取当前用户id,用户信息
        Long currentId = BaseContext.getCurrentId();
        User user = userService.getById(currentId);

        //2.获取地址簿信息
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        if(addressBook==null){
            throw new CustomException("用户地址信息有误，不能下单");
        }

        //3.获取购物车商品列表
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId,currentId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(shoppingCartLambdaQueryWrapper);
        if(shoppingCarts==null || shoppingCarts.size()==0){
            throw new CustomException("购物车为空，不能下单");
        }


        //4.向订单表和订单明细表插入数据 ,order和orderDetail填充数据
        long orderId = IdWorker.getId();//生成订单id
        //java.util.concurrent.atomic 的包,主要用于在高并发环境下的高效程序处理,来帮助我们简化同步处理.
        AtomicInteger amount = new AtomicInteger(0);

        //订单明细表，遍历购物车商品计算总金额，同时给订单明细表对象赋值
        List<OrderDetail> orderDetails = shoppingCarts.stream().map( (item) -> {
            //订单详细对象
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId( orderId );//订单id主键
            orderDetail.setNumber( item.getNumber() );//订单号
            orderDetail.setDishFlavor( item.getDishFlavor());//菜品口味
            orderDetail.setDishId( item.getDishId()); //菜品id
            orderDetail.setSetmealId( item.getSetmealId()); //套餐id
            orderDetail.setName( item.getName()); //套餐/菜品名
            orderDetail.setImage( item.getImage()); //图片
            orderDetail.setAmount( item.getAmount() );//商品单价
            //总金额计算累加，单价 * 数量 转为整型计算
            amount.addAndGet( item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect( Collectors.toList());//多个订单明细对象转为list集合


        //订单数据赋值
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        //支付时间，因为没有支付功能，所以设置当前时间
        orders.setCheckoutTime( LocalDateTime.now() );
        //订单的状态： 1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setStatus(2);//订单状态
        orders.setAmount(new BigDecimal(amount.get()));//总价格
        orders.setUserId(currentId);//用户id
        orders.setNumber(String.valueOf(orderId));//订单号
        orders.setUserName(addressBook.getConsignee());
        orders.setConsignee(addressBook.getConsignee());//收货人
        orders.setPhone(addressBook.getPhone());
        //收货地址拼接
        orders.setAddress( (addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName() )
                + ( addressBook.getCityName() == null ? "" : addressBook.getCityName() )
                + ( addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName() )
                + ( addressBook.getDetail() == null ? "" : addressBook.getDetail() ) );
        //插入订单
        this.save(orders);

        //订单明细插入
        orderDetailService.saveBatch(orderDetails);


        //清空购物车
        shoppingCartService.remove(shoppingCartLambdaQueryWrapper);
    }
}
